package army;

import java.util.Random;

public class Army {
	public static final int NSQUADS = 5;
	public static final int FIRST_ATTACK_SQUAD = 1;
	private final int[] unitsInSquad = new int[NSQUADS];
	Random random;
	
	public Army(
			int unitsInSquad0, 
			int unitsInSquad1, 
			int unitsInSquad2, 
			int unitsInSquad3, 
			int unitsInSquad4,
			Random random) {
		
		unitsInSquad[0] = unitsInSquad0;
		unitsInSquad[1] = unitsInSquad1;
		unitsInSquad[2] = unitsInSquad2;
		unitsInSquad[3] = unitsInSquad3;
		unitsInSquad[4] = unitsInSquad4;
		this.random = random;
	}
	
	public Army(Army anotherArmy){
		System.arraycopy(anotherArmy.unitsInSquad, 0, this.unitsInSquad, 0, NSQUADS);
		this.random = anotherArmy.random;
	}
	
	public int getUnitsInSquad(int i) {
		return unitsInSquad[i];
	}
	
	public int getArmySize() {
		int armySize = 0;
		for (int unitLevel = 0; unitLevel < NSQUADS; unitLevel++) {
			armySize += unitsInSquad[unitLevel];
		}
		return armySize;
	}
	
	public boolean isAlive() {
		return getArmySize() > 0 ? true : false;
	}
	
	public int strike(){
		int hits = 0;
		
		for (int unitLevel = FIRST_ATTACK_SQUAD; unitLevel < Army.NSQUADS; unitLevel++) {

			for (int unit = 0; unit < unitsInSquad[unitLevel]; unit++) {
				if (throwDice() <= unitLevel) {
					hits++;
				}
			}
		}
		
		return hits;
	}
	
	public int throwDice() {
		return random.nextInt(6) + 1;
	}
	
	public void subtractHits(int hits) {

		for (int unitLevel = 0; unitLevel < NSQUADS; unitLevel++) {
			if( hits <= 0)  { break; }
			if( !isAlive()) { break; }

			if (unitsInSquad[unitLevel] >= hits) {
				unitsInSquad[unitLevel] -= hits;
				hits = 0;
			} else {
				hits -= unitsInSquad[unitLevel];
				unitsInSquad[unitLevel] = 0;
			}
		}
	}
	

}
